<?php defined('SYSPATH') or die('No direct script access.');

/**
 *  微信小程序广告配置
 */
class Controller_Wxxcx  extends Stourweb_Controller
{
    public function before()
    {
        parent::before();
    }

    protected function get_client()
    {
        return array(
            0 => '微信小程序',
            1 => '移动H5',
            2 => '字节跳动小程序'
        );
    }

    public function action_index()
    {
        $action = $this->params['action'];

        if (empty($action)) {
            $prefix = $this->params['prefix'];
            $data = include CACHE_DIR . 'newtravel/category.php';
            $kindname = '首页';
            foreach ($data['page'] as $item) {
                if ($prefix == "s_{$item['page_name']}") {
                    $kindname =$item['name'];
                    break;
                }
            }
            $models =  DB::select('id', 'modulename')->from('model')->where('isopen','=',1)->execute()->as_array();
            $this->assign('models', $models);
            $this->assign('kindname', $kindname);
            $this->assign('prefix', $prefix);
            $this->assign('client', $this->get_client());
            $this->assign('ads', DB::select()->from('advertise_5x')->where('id', '=', $this->params['id'])->execute()->current());
            $this->display('stourtravel/wxxcx/index');
        }
        if ($action == 'update') {
            $id = Arr::get($_POST, 'id');
            $val = Arr::get($_POST, 'val');
            $field = Arr::get($_POST, 'field');
            if ($field == 'displayorder') {
                $val =  !empty($val) ?  $val : 9999;
            }
            DB::update('xcx_ads')->where("id=$id")->set(array($field => $val))->execute();
            echo 'ok';
        }
    }

    /**
     * @function  指定产品
     */
    public function  action_add_product()
    {
        $action = $this->params['action'];
        $prefix = $this->params['prefix'];
        $modelid = self::get_typeid($prefix);
        $number = $this->params['number'];
        if (!$action) {
            $models =  DB::select('id', 'modulename')->from('model')->where('isopen','=',1)->and_where('is_orderable','=',1)->execute()->as_array();
            $this->assign('models', $models);
            $this->assign('typeid', $modelid);
            $this->assign('prefix', $prefix);
            $this->assign('number', $number);
            $this->display('stourtravel/wxxcx/prolist');
        }
        if ($action == 'read') {
            // 获取线路 酒店 驻车 门票 中的第一个应用(防止应用没有)
            $models =  DB::select('id', 'modulename')->from('model')->where('isopen','=',1)->execute()->as_array();
            $typeid = Arr::get($_GET, 'typeid') ? Arr::get($_GET, 'typeid') : $models[0]['id'];
            $modeldata = DB::select('maintable', 'modulename')->from('model')->where('id', '=', $typeid)->execute()->current();
            $protable = $modeldata['maintable'];
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $keyword = Arr::get($_GET, 'keyword');
            $w = "a.id is not null and ishidden=0 ";
            if ($protable == 'model_archive') {
                $w .= " and a.typeid=$typeid";
            }
            $w .= empty($keyword) ? '' : " and a.title like '%{$keyword}%'";
            $totalcount_arr = DB::query(Database::SELECT, "select count(*) as num from sline_$protable a where $w")->execute()->as_array();
            $sql = "select a.id,a.title from sline_$protable as a   LEFT JOIN  sline_allorderlist as b   ON (a.id=b.aid and b.typeid=$typeid) where $w    ORDER BY IFNULL(b.displayorder,9999) ASC,a.modtime DESC,a.addtime DESC  limit $start,$limit";

            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();

            foreach ($list as &$l) {
                $l['typename'] = $modeldata['modulename'];
                $l['bh'] = St_Product::product_series($l['id'], "{$typeid}"); //编号
            }
            $result['total'] = $totalcount_arr[0]['num'];
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
        if ($action == 'del') {
            $id = Arr::get($_POST, 'id');
            if (is_numeric($id)) {
                DB::delete('xcx_ads')->where('id', '=', $id)->execute();
            }
            echo 'ok';
        }
    }
    // 获取关联的产品
    public function action_pro_list()
    {

        $typeid = Arr::get($_GET, 'typeid') ? Arr::get($_GET, 'typeid') : 0;
        $id = Arr::get($_GET, 'id');
        $page = Arr::get($_GET, 'page');
        $prefix = Arr::get($_GET, 'prefix');
        $number = Arr::get($_GET, 'number', 1);
        $limit = 10;
        $start = ($page - 1) * $limit;
        $keyword = Arr::get($_GET, 'keyword');
        $w = "a.id is not null and a.prefix = '{$prefix}' and a.number={$number}";
        $w .= empty($keyword) ? '' : " and a.protitle like '%{$keyword}%'";
        $w .= empty($typeid) ? '' : ' and a.typeid=' . $typeid;
        $totalcount_arr = DB::query(Database::SELECT, "select count(*) as num from sline_xcx_ads a where $w")->execute()->as_array();
        $sql = "select a.* from sline_xcx_ads as a where $w order by a.id desc limit $start,$limit";

        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
        foreach ($list as &$l) {
            $modeldata = DB::select('modulename')->from('model')->where('id', '=', $l['typeid'])->execute()->current();
            $l['typename'] = $modeldata['modulename'];
            $l['bh'] = St_Product::product_series($l['id'], "{$l['typeid']}"); //编号
        }
        $result['total'] = $totalcount_arr[0]['num'];
        $result['page'] = $page;
        $result['pagesize'] = 10;
        $result['lists'] = $list;
        $result['success'] = true;
        echo json_encode($result);
    }
    /**
     * @function 保存关联产品信息
     */
    public function action_ajax_prolist_save()
    {

        $subdata = Arr::get($_POST, 'subdata');
        $prefix = Arr::get($_POST, 'prefix');
        $subdata = explode(',', $subdata);
        foreach ($subdata as $data) {
            $data = explode('_', $data);
            $set_arr = array('proid', 'typeid', 'protitle', 'prefix','number');
            $val_arr = array($data[1], $data[0], $data[2], $prefix,Arr::get($_POST, 'number'));
            DB::insert('xcx_ads', $set_arr)->values($val_arr)->execute();
        }
        echo json_encode(array('status' => 'yes'));
    }

    //图片上传是保存
    public function action_ajax_upload_save()
    {
        $ads = explode(',', Arr::get($_POST, 'adsrc'));
        foreach ($ads as $v) {
            $data = array(
                'number' => Arr::get($_POST, 'number', 1),
                'prefix' => Arr::get($_POST, 'prefix'),
                'adsrc' => $v,
            );
            DB::insert('xcx_ads', array_keys($data))->values(array_values($data))->execute();
        }
        echo json_encode(array('status' => 'yes'));
    }

    /**
     * 获取类型ID
     */
    public static function get_typeid($prefix)
    {
        if ($prefix == 's_index') {
            $str = '1,2,3,4,5,8,13,104,118,106,101,114';
        } elseif ($prefix == 's_line_index') {
            $str = '1';
        } elseif ($prefix == 's_hotel_index') {
            $str = '2';
        } elseif ($prefix == 's_car_index') {
            $str = '3';
        } elseif ($prefix == 's_article_index') {
            $str = '4';
        } elseif ($prefix == 's_spot_index') {
            $str = '5';
        } elseif ($prefix == 's_techan_index') {
            $str = '118';
        } elseif ($prefix == 's_ship_index') {
            $str = '104';
        } elseif ($prefix == 's_visa_index') {
            $str = '8';
        } elseif ($prefix == 's_guide_index') {
            $str = '106';
        } elseif ($prefix == 's_notes_index') {
            $str = '101';
        } elseif ($prefix == 's_outdoor_index') {
            $str = '114';
        } elseif ($prefix == 's_malls_index') {
            $str = '21';
        }
        elseif ($prefix == 's_tuan_index')
        {
            $str = '13';
        }
        elseif ($prefix == 's_customize_index')
        {
            $str = '1,2,3,4,5,8,13,104,118,106,101,114';
        }
        elseif ($prefix == 's_dest_index')
        {
            $str = '1,2,3,4,5,8,13,104,118,106,101,114';
        }
        elseif ($prefix == 'strategy_index')
        {
            $str = '1,2,3,4,5,8,13,104,118,106,101,114';
        }
        elseif ($prefix == 's_integral_index')
        {
            $str = '107';
        }
        return $str;
    }


    // 微信小程序自定义导航
    public function action_custom_nav()
    {
        $action = $this->params['action'];
        if (empty($action)) {
            $this->display('stourtravel/wxxcx/custom_nav');
        } else if ($action == 'read') {
            $node = Arr::get($_GET, 'node');
            $list = array();
            if ($node == 'root') //属性组根
            {
                $list = ORM::factory("xcx_nav")->order_by(DB::expr("ifnull(m_displayorder, 9999) asc"))->get_all();
                foreach ($list as $k => $v) {
                    $list[$k]['leaf'] = true;
                    $list[$k]['allowDrag'] = false;
                    $list[$k] = $this->_get_menu_ico($v);
                }
                $list[] = array(
                    'leaf' => true,
                    'id' => '0add',
                    'm_title' => '<button class="dest-add-btn df-add-btn" onclick="addSub(0)">添加</button>',
                    'allowDrag' => false,
                    'allowDrop' => false,
                    'm_displayorder' => 'add',
                    'm_isopen' => 'add'
                );
            }
            echo json_encode(array('success' => true, 'text' => '', 'children' => $list));
        } else if ($action == 'addsub') //添加子级
        {
            $nav_id = intval(Arr::get($_POST, 'nav_id'));
            $nav_name = Arr::get($_POST, 'nav_name');
            $litimg = Arr::get($_POST, 'litimg');
            $nav_mode = Arr::get($_POST, 'nav_mode');
            $nav_param = Arr::get($_POST, 'nav_param');
            $nav_path = Arr::get($_POST, 'nav_path');
            if ($nav_id) {
                $model = ORM::factory("xcx_nav", $nav_id);
            } else {
                $model = ORM::factory("xcx_nav");
            }
            $model->m_title = $nav_name;
            $model->m_mode = $nav_mode;
            $model->m_ico = $litimg;
            $model->m_url = $nav_path;
            $model->m_params = $nav_param;
            $model->save();
            if ($model->saved()) {
                $model->reload();
                echo json_encode($model->as_array());
            }
        } else if ($action == 'save') //保存修改
        {
            $rawdata = file_get_contents('php://input');
            $field = Arr::get($_GET, 'field');
            $data = json_decode($rawdata);
            $id = $data->id;
            if ($field) {
                $model = ORM::factory("xcx_nav", $id);
                if ($model->id) {
                    $model->$field = $data->$field;
                    $model->save();
                    if ($model->saved())
                        echo 'ok';
                    else
                        echo 'no';
                }
            }
        } else if ($action == 'delete') //属性删除
        {
            $rawdata = file_get_contents('php://input');
            $data = json_decode($rawdata);
            $id = $data->id;
            if (!is_numeric($id)) {
                echo json_encode(array('success' => false));
                exit;
            }
            $model = ORM::factory("xcx_nav", $id);
            $model->delete();
        } else if ($action == 'update') //更新操作
        {
            $id = Arr::get($_POST, 'id');
            $field = Arr::get($_POST, 'field');
            $val = Arr::get($_POST, 'val');
            $model = ORM::factory("xcx_nav", $id);
            if ($model->id) {
                $model->$field = $val;
                if ($field == 'm_displayorder') {
                    $val = intval($val) <= 0 ? 9999 : intval($val);
                    $model->$field = $val;
                }
                $model->save();
                if ($model->saved())
                    echo 'ok';
                else
                    echo 'no';
            }
        }
    }


    /**
     * @function 获取菜单的图片
     * @param $menu
     * @return mixed
     */
    private function _get_menu_ico($menu)
    {
        if (!$menu['m_ico']) {
            $menu['m_ico'] = Common::get_menu_no_ico($menu['m_typeid']);
        }
        $menu['default_ico'] = Common::get_menu_no_ico($menu['m_typeid']);
        return $menu;
    }


    // 微信小程序设置导航
    public function action_dialog_set_xcx_nav()
    {
        // 微信小程序导航
        $xcx_page = Model_Xcx_Nav::get_xcx_page();
        // 已保存的导航
        $navid = intval(Arr::get($_GET, 'navid'));
        $info = array();
        if ($navid) {
            $info = DB::select()->from("xcx_nav")->where("id", "=", $navid)->execute()->current();
        }

        // 小程序页面
        $_xcx_default_page = $xcx_page['default_page']; // 默认页面
        $_xcx_model_page = $xcx_page['model_page']; // 应用页面 需要判断是否有该应用
        $xcx_page = array();
        // 检查
        foreach ($_xcx_model_page as &$v) {
            // 检查是否有该应用
            $check_model = Model_Model::is_install_model($v['typeid']);
            if ($check_model == 1) {
                array_push($xcx_page, $v);
            }
        }
        $xcx_page = array_merge($xcx_page, $_xcx_default_page);

        $this->assign("info", $info);
        $this->assign("xcx_page", $xcx_page);
        $this->display("stourtravel/wxxcx/dialog_xcx_nav");
    }
}
